import { createRouter, createWebHashHistory } from 'vue-router'
import { store } from '@/store'
import { ElMessage } from 'element-plus'

// 页面组件懒加载
const Home = () => import('@/views/Home.vue')
const Products = () => import('@/views/Products.vue')
const ProductDetail = () => import('@/views/ProductDetail.vue')
const Cart = () => import('@/views/Cart.vue')
const Checkout = () => import('@/views/Checkout.vue')
const Brands = () => import('@/views/Brands.vue')
const About = () => import('@/views/About.vue')
const Service = () => import('@/views/Service.vue')
const Auth = () => import('@/views/Auth.vue')

const routes = [
  {
    path: '/',
    name: 'Home',
    component: Home
  },
  {
    path: '/products',
    name: 'Products',
    component: Products
  },
  {
    path: '/product/:id',
    name: 'ProductDetail',
    component: ProductDetail,
    props: true
  },
  {
    path: '/cart',
    name: 'Cart',
    component: Cart,
    meta: { requiresAuth: true }
  },
  {
    path: '/checkout',
    name: 'Checkout',
    component: Checkout,
    meta: { requiresAuth: true }
  },
  {
    path: '/brands',
    name: 'Brands',
    component: Brands
  },
  {
    path: '/about',
    name: 'About',
    component: About
  },
  {
    path: '/service',
    name: 'Service',
    component: Service
  },
  {
    path: '/login',
    name: 'Login',
    component: Auth,
    meta: { hideNavbar: true }
  },
  {
    path: '/register',
    name: 'Register',
    component: Auth,
    meta: { hideNavbar: true }
  },
  {
    path: '/auth',
    name: 'Auth',
    component: Auth,
    meta: { hideNavbar: true }
  }
]

const router = createRouter({
  history: createWebHashHistory(),
  routes,
  scrollBehavior(to, from, savedPosition) {
    if (savedPosition) {
      return savedPosition
    } else {
      return { top: 0 }
    }
  }
})

// 路由守卫
router.beforeEach((to, from, next) => {
  // 检查登录状态
  store.checkAuth()
  
  // 如果是登录页面且已登录，重定向到首页
  if ((to.name === 'Login' || to.name === 'Register' || to.name === 'Auth') && store.user.isLogin) {
    next('/')
    return
  }
  
  // 检查是否需要登录
  if (to.meta.requiresAuth && !store.user.isLogin) {
    ElMessage.warning('请先登录后再访问该页面')
    next({
      name: 'Login',
      query: { redirect: to.fullPath }
    })
    return
  }
  
  next()
})

export default router
